package com.atguigu.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.eduservice.entity.EduSubject;
import com.atguigu.eduservice.entity.excel.SubjectData;
import com.atguigu.eduservice.service.EduSubjectService;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    /**
     * 监听器无法交给spring管理
     * 监听器中无法注入Service
     * */
    public EduSubjectService subjectService;

    public SubjectExcelListener(){}

    public SubjectExcelListener(EduSubjectService subjectService) {
        this.subjectService = subjectService;
    }

    /**
     * 一行一行读取表格内容（不读取表头，即不读取第一行）
     * 读取一行执行一次该方法
     * */
    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001,"文件数据为空");
        }

        EduSubject existOneSubject = this.existOneSubject(subjectService, subjectData.getOneSubjectName());
        if (existOneSubject == null){
            existOneSubject = new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(subjectData.getOneSubjectName());
            subjectService.save(existOneSubject);
        }

        String pid=existOneSubject.getId();//获取父id
        EduSubject existTwoSubject = this.existTwoSubject(subjectService, subjectData.getTwoSubjectName(), pid);
        if (existTwoSubject == null){
            existTwoSubject = new EduSubject();
            existTwoSubject.setParentId(pid);
            existTwoSubject.setTitle(subjectData.getTwoSubjectName());
            subjectService.save(existTwoSubject);
        }
    }

    /**
     * 查看数据表中是否已有一级分类
     * */
    private EduSubject existOneSubject(EduSubjectService subjectService,String name){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();//mybatisplus中的条件类
        wrapper.eq("title",name);//eq为等于
        wrapper.eq("parent_id","0");
        EduSubject oneSuject = subjectService.getOne(wrapper);
        return oneSuject;
    }

    /**
     * 查看数据表中是否已有多级级分类
     * */
    private EduSubject existTwoSubject(EduSubjectService subjectService,String name,String parentId){
        QueryWrapper<EduSubject> wrapper = new QueryWrapper<>();//mybatisplus中的条件类
        wrapper.eq("title",name);//eq为等于
        wrapper.eq("parent_id",parentId);
        EduSubject twoSuject = subjectService.getOne(wrapper);
        return twoSuject;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
